package com.ysd.lis.controller.pub;


import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ysd.common.Result;
import com.ysd.lis.annotation.LogDetail;
import com.ysd.lis.aspect.OperationType;
import com.ysd.lis.dto.PubEmployeeDto;
import com.ysd.lis.entity.PubEmployee;
import com.ysd.lis.entity.SysInterface;
import com.ysd.lis.entity.SysOrgDepartment;
import com.ysd.lis.entity.SysUser;
import com.ysd.lis.mapper.sys.SysInterfaceMapper;
import com.ysd.lis.request.PubEmployeeAddParam;
import com.ysd.lis.request.PubEmployeePageParam;
import com.ysd.lis.request.UserInfoVo;
import com.ysd.lis.service.PubEmployeeService;
import com.ysd.util.PropertySlash;
import com.ysd.util.RedisUserManager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 员工表
 * 前端控制器
 * </p>
 *
 * @author LiuQi
 * @since 2023-10-19
 */
@Api(tags = "员工信息")
@RestController
@RequestMapping("/api/sys/hisEmployee")
public class PubEmployeeController extends BaseController {

    @Value("${picturePath}")
    private String picturePath;
    private static final int MAX_POST_SIZE = 20 * 1024 * 1024;

    @Autowired
    private PubEmployeeService hisEmployeeService;
    @Autowired
    SysInterfaceMapper sysInterfaceMapper;

    @ApiOperation("根据组织机构查询员工列表")
    @GetMapping("/findAllHisEmployeeListByOrgDept")
    public Result findAllHisEmployeeListByOrgDept(PubEmployeePageParam pubEmployeePageParam) {
        return hisEmployeeService.findAllHisEmployeeListByOrgDept(pubEmployeePageParam);
    }

    @ApiOperation("根据角色id查询员工列表")
    @GetMapping("/finAllHisEmployeeList/{roleId}")
    public Result finAllHisEmployeeList(@PathVariable("roleId") String roleId) {
        return hisEmployeeService.finAllHisEmployeeList(roleId);
    }

    @ApiOperation("查询所有员工列表")
    @GetMapping("/finAllHisEmployeeList")
    public Result finAllHisEmployeeList() {
        return hisEmployeeService.finAllHisEmployeeList();
    }

    /**
     * 危急值提醒程序用
     *
     * @return
     */
    @ApiOperation("查询所有员工列表")
    @PostMapping("/finAllHisEmployees")
    public List<UserInfoVo> finAllHisEmployees(@RequestBody String info) {
        return hisEmployeeService.finAllHisEmployees(info);
    }

    @ApiOperation("添加员工")
    @PostMapping("/addHisEmployee")
    @LogDetail(operationType = OperationType.INSERT, module = "添加员工")
    public Result addHisEmployee(@RequestBody PubEmployeeAddParam pubEmployeeAddParam) {
        return hisEmployeeService.addHisEmployee(pubEmployeeAddParam);
    }

    @ApiOperation("编辑员工")
    @PutMapping("/editHisEmployee")
    @LogDetail(operationType = OperationType.UPDATE, module = "编辑员工")
    public Result editHisEmployee(@RequestBody PubEmployeeAddParam pubEmployeeAddParam) {
        return hisEmployeeService.editHisEmployee(pubEmployeeAddParam);
    }

    @ApiOperation("删除员工")
    @DeleteMapping("/deleteHisEmployeeById/{id}")
    @LogDetail(operationType = OperationType.UPDATE, module = "删除员工")
    public Result deleteHisEmployeeById(@PathVariable("id") @ApiParam("员工id") String id) {
        return hisEmployeeService.deleteHisEmployeeById(id);
    }

    @ApiOperation("根据员工id查询员工信息")
    @GetMapping("/getHisEmployeeInfoById/{id}")
    public Result getHisEmployeeInfoById(@PathVariable("id") @ApiParam("员工id") String id) {
        return hisEmployeeService.getHisEmployeeInfoById(id);
    }

    @ApiOperation("根据员工id查询关联用户")
    @GetMapping("/getUserListByHisEmployeeId/{id}")
    public Result getUserListByHisEmployeeId(@PathVariable("id") @ApiParam("员工id") String id) {
        return hisEmployeeService.getUserListByHisEmployeeId(id);
    }

    @ApiOperation("根据员工id查询关联部门")
    @GetMapping("/getDeptListByHisEmployeeId/{id}")
    public Result getDeptListByHisEmployeeId(@PathVariable("id") @ApiParam("员工id") String id) {
        return hisEmployeeService.getDeptListByHisEmployeeId(id);
    }

    @ApiOperation("根据用户id或者员工id删除关联关系")
    @DeleteMapping("/deleteUserContactById/{id}/{type}")
    @LogDetail(operationType = OperationType.DELETE, module = "根据用户id或者员工id删除关联关系")
    public Result deleteUserContactById(@PathVariable("id") @ApiParam("id") String id, @PathVariable("type") @ApiParam("type") String type) {
        return hisEmployeeService.deleteUserContactById(id, type);
    }

    @ApiOperation("根据用户id和员工id添加关联关系")
    @PutMapping("/addContactUserInfo/{hisEmployeeId}/{userId}")
    @LogDetail(operationType = OperationType.UPDATE, module = "根据用户id和员工id添加关联关系")
    public Result addContactUserInfo(@PathVariable("hisEmployeeId") @ApiParam("员工id") String hisEmployeeId, @PathVariable("userId") @ApiParam("用户id") String userId) {
        return hisEmployeeService.addContactUserInfo(hisEmployeeId, userId);
    }

    @ApiOperation("根据部门id和员工id添加关联关系")
    @PutMapping("/addContactDeptInfo/{hisEmployeeId}/{deptId}")
    @LogDetail(operationType = OperationType.UPDATE, module = "根据部门id和员工id添加关联关系")
    public Result addContactDeptInfo(@PathVariable("hisEmployeeId") @ApiParam("员工id") String hisEmployeeId, @PathVariable("deptId") @ApiParam("部门id") String deptId) {
        return hisEmployeeService.addContactDeptInfo(hisEmployeeId, deptId);
    }

    @ApiOperation("根据部门id或者id删除关联关系")
    @DeleteMapping("/deleteDeptContactById/{id}/{type}")
    @LogDetail(operationType = OperationType.DELETE, module = "根据部门id或者id删除关联关系")
    public Result deleteDeptContactById(@PathVariable("id") @ApiParam("id") String id, @PathVariable("type") @ApiParam("type") String type) {
        return hisEmployeeService.deleteDeptContactById(id, type);
    }

    @ApiOperation("更新授权码")
    @PutMapping("/updateEmpowerNum/{id}/{empowerNum}")
    @LogDetail(operationType = OperationType.UPDATE, module = "更新授权码")
    public Result updateEmpowerNum(@PathVariable("id") @ApiParam("员工id") String id, @PathVariable("empowerNum") @ApiParam("授权码") String empowerNum) {
        return hisEmployeeService.updateEmpowerNum(id, empowerNum);
    }

    @ApiOperation("设置默认部门")
    @PutMapping("/setDefaultDeptByHisEmployeeId/{id}/{employeeId}")
    @LogDetail(operationType = OperationType.UPDATE, module = "设置默认部门")
    public Result setDefaultDeptByHisEmployeeId(@PathVariable("id") @ApiParam("id") String id, @PathVariable("employeeId") @ApiParam("员工id") String employeeId) {
        return hisEmployeeService.setDefaultDeptByHisEmployeeId(id, employeeId);
    }


    @ApiOperation("上传电子签名")
    @PostMapping("/uploadSignatureFile")
    @LogDetail(operationType = OperationType.UPDATE, module = "上传电子签名")
    public Result uploadSignatureFile(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) throws IOException {
        String id = request.getParameter("id");
        if (file == null) {
            return Result.fail("文件不能为空");
        }
        // 文件限制10M
        long size = file.getSize();
        if (size > MAX_POST_SIZE) {
            return Result.fail("文件最大为 10M！");
        }
//        String folder = picturePath + "/" + DateUtil.format(new Date(), "yyyyMM") + File.separator;
        String folder = picturePath + PropertySlash.getSlash();
        if (!FileUtil.exist(folder)) {
            FileUtil.mkdir(folder);
        }
        String fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddhhmmssSSS")) + file.getOriginalFilename();
        String path = folder + fileName;
        File files = new File(path);
        if (FileUtil.exist(files)) {
            return Result.fail("文件已存在");
        }
        File file1 = FileUtil.writeBytes(file.getBytes(), path);
        if (file1.length() < 0) {
            return Result.fail("文件上传失败");
        }
        return hisEmployeeService.uploadSignatureFile(id, path);
    }

    @ApiOperation("获取电子签名连接")
    @GetMapping("/getSignatureFile/{id}")
    public Result getSignatureFile(@PathVariable("id") String id) throws IOException {
        return hisEmployeeService.getSignatureFilePath(id);
    }

    @ApiOperation("分页查询")
    @GetMapping("/getEmployeePageList")
    public Result getEmployeePageList(PubEmployeePageParam pageParam) {
        return hisEmployeeService.getEmployeePageList(pageParam);
    }

    @ApiOperation("查询")
    @GetMapping("/getPubEmployeeList")
    public Result getPubEmployeeList(PubEmployeePageParam pageParam) {
        return hisEmployeeService.getPubEmployeeList(pageParam);
    }

    @ApiOperation("根据用户code与授权码获取用户信息")
    @GetMapping("/getEmployeeByCodeAndNum")
    public Result getEmployeeByCodeAndNum(PubEmployee employee) {
        return hisEmployeeService.getEmployeeByCodeAndNum(employee);
    }

    @ApiOperation("同步医生")
    @GetMapping("/syncPubEmployees")
    public Result syncPubEmployees() {
        return hisEmployeeService.syncPubEmployees();
    }


    @GetMapping("/getInterfaceData")
    public Result getData(String url, String code, String idNo, String orgId, String patNo,String reqNo) {
        SysUser user = RedisUserManager.getUser();
        Map map = new HashMap<>();
        map.put("methodCode", code);
        map.put("idNo", idNo);
        map.put("orgId", orgId);
        map.put("patNo", patNo);
        map.put("username", user.getUsername());
        map.put("realname", user.getRealname());
        map.put("reqNo",reqNo);
        LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysInterface::getDelFlag, 0);
        wrapper.eq(SysInterface::getIsEnable, 1);
        wrapper.eq(SysInterface::getOrgId, orgId);
        List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
        List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());
        try {
            if (CollectionUtils.isNotEmpty(collect)) {
                for (String webUrl : collect) {
                    String body = HttpUtil.createPost(webUrl + url).body(JSONUtil.toJsonStr(map)).contentType("application/json").execute().body();
                    return Result.succ(body);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("接口管理平台异常,请检查");
        }
        return Result.fail("失败");
    }

    @ApiOperation("批量添加用户")
    @PostMapping("/hisEmployeeBatchCreateUser")
    public Result hisEmployeeBatchCreateUser(@RequestBody PubEmployeeDto dto) {
        return hisEmployeeService.hisEmployeeBatchCreateUser(dto);
    }

    @ApiOperation("批量添加用户")
    @PostMapping("/hisEmployeeBatchCreateHSUser")
    public Result hisEmployeeBatchCreateHSUser(@RequestBody PubEmployeeDto dto) {
        return hisEmployeeService.hisEmployeeBatchCreateHSUser(dto);
    }
}
